<?php
	/* Set up the link to the DB */
   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/Gen_Scripts/database.php";
   include_once($path);
   
/*************************************************************
                           Utilities  
 *************************************************************/

/* Utility to clean incoming data */
function clean_data($string) {
dblogin();
  if (get_magic_quotes_gpc()) {
    $string = stripslashes($string);
  }
  $string = strip_tags($string);
  return mysql_real_escape_string($string);
}
 
 
 /* Test to see if logged in */
function loggedin(){
/* Quick true/false on if the person is logged in */
if($_SESSION['LOGGEDIN'] == 'YES')
   return true;
else
  return false;
}


/*************************************************************
                       Header + Footer  
 *************************************************************/

/*  Menu  */
function show_menu($page){

		echo '<div  id="menu">';
			echo '<div class="nav" id="home"'; 
				if($page == "index"){echo 'class="current"';} 
			echo '><a href="index.php#tourny"></a></div>';
			echo '<div class="nav" id="gamelist"'; 
				if($page == "game"){echo 'class="current"';} 
			echo '><a href="index.php#gamevote"></a></div>';
			echo '<div class="nav" id="gamepoint"'; 
				if($page == "gamelist"){echo 'class="current"';} 
			echo '><a href="index.php#gp_stats"></a></div>';
/*			echo '<div id="forum"'; 
			echo '><a href="index.php"></a></div>';


		/* Stuff in the top right corner */

		 if(loggedin()){
			include('Gen_Scripts/avitar_sign_out.php');
			if($_SESSION['TYPE'] == 'A'){
			/*	echo '<div id="editself"><a href="manage.php#gp_edit"></a></div>';*/
				echo '<div id="editself"><a href="manage.php#gp_add"></a></div>';
			/*	echo '<div id="editself"><a href="manage.php#tourny_edit"></a></div>';*/
				echo '<div id="editself"><a href="manage.php#t_add_ajax"></a></div>';
			}
/*			echo '<div id="editgame"><a href="index.php"></a></div>';
			echo '<div id="addgame"><a href="Gen_Scripts/sub_game_form.php?keepThis=true&TB_iframe=true&height=286&width=600&modal=true" 
					title="" class="thickbox"></a></div>';*/
		 }else{
			include('Gen_Scripts/login_form.php');
		 }
		 
		echo '</div>';
}

/* Footer */
function show_footer(){
echo '
		<div id="footer">
			<a rel="license" href="http://creativecommons.org/licenses/by-nc/3.0/us/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc/3.0/us/88x31.png" /></a>&nbsp;&nbsp;<a href="http://www.xaktek.com">Xaksei</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		</div>
    ';
}


/* Utility to update value(s) in a table */
function update($table, $field, $val, $where, $condition){
	dblogin();
	$query = 
	"select ".$field." from ".$table." p where p.".$where." = ".$condition;
	if($result = mysql_query($query)){
		if($row = mysql_fetch_array($result)){
			$upquery = 
				"update ".$table." p
				  set ".$field." =  ".$val."
				 where p.".$where." = ".$condition;
			$upresult = mysql_query($upquery);
		}
	}	
}


/* Format of the cookie
[Userid][encrypted pass]
[000][sha1 of password]
*/


function max_tid(){
	dblogin();
	$query = 
	"select max(t_id) as \"TID\" from TOURNY";
	if($result = mysql_query($query)){
		if($row = mysql_fetch_array($result)){
			return $row['TID'];
		}
	}
	return 1;
}

/*************************************************************
                           Login stuff  
 *************************************************************/
function login(){
/* does the action of testing for user
	Saving cookie and session*/
	dblogin();

	/* Check the cookie */
	if($_COOKIE['fnt_id'] != '' && $_SESSION['LOGGEDIN'] != 'YES'){
		$id =  $_COOKIE['fnt_id'];
		$key = $_COOKIE['fnt_key'];
		$query = 
		"select c.login, c.key from db56987_fnt.cookie c where c.id = $id";
		$qkey = '';
		$login = '';
		if($result = mysql_query($query)){
 			if($row = mysql_fetch_array($result)){
				$qkey = $row["key"];
				$login = $row["login"];
   	 		}
		}
		if($key == $qkey){
			$queryl = 
			"select name from db56987_fnt.players where login = '$login'";
			if($resultl = mysql_query($queryl)){
				if($rowl = mysql_fetch_array($resultl)){
					setup_session($login, $row["name"]);
				   return;
				}
			}
		}
	}
	

	if($_POST['LoginButton'] == 'Login'){
		/* Gather and sanitize input */
		$user = $_POST['user'];
		$inputted_pass = $_POST['pass'];
		
		$user = clean_data($user);
  		$inputted_pass  = clean_data($inputted_pass);

		$user_id = sha1(($user));		
		/*$user_id = sha1(strtolower($user));*/
	
		/* Grab info from the DB */		
		$query = 
		"select player_id, name, pass, type from PLAYERS where login_id = '$user_id'";
		$pass = '';
		$name = '';
		if($result = mysql_query($query)){
	 		if($row = mysql_fetch_array($result)){
				$name = $row["name"];
				$pass = $row["pass"];
				$player_id = $row["player_id"];
				$type = $row["type"];
	    	}
 		}		
		
		/* Test the input */
		if(sha1($inputted_pass) == $pass and $pass != ''){
			setup_cookies_session($player_id, $user, $name, $pass,$type);
		}	
    }	
}

/*  Creates a cookie and session */
function setup_cookies_session($usernum, $user, $name, $pass,$type){
	setup_session($usernum, $user,$name,$type);
	
	  
	/* Get the numbers to put in the cookies*/
	$cookie_key = sha1($user.$pass);
	$duplicate = true;
	while($duplicate){
		$duplicate = false;
		$cookie_id= rand(50,1029340);
		/* Verify that the id is NOT already in the database, if it is, try again*/
		$query = 
		"select id from db56987_cookie where id = $id";
		if($result = mysql_query($query)){
			if($row = mysql_fetch_array($result)){
				if($row["id"] != ''){
					$duplicate = true;
				}
			}
		}
	}
	
	setcookie("fnt_key", $cookie_key, time()+(24*3600));  /* expire in 24 hours */
	setcookie("fnt_id",$cookie_id, time()+(24*3600));  /* expire in 24 hours */
	
	/* put the cookie into the database*/
	$updateq = 
	"insert into cookie values ($cookie_id, '$cookie_key', '$user', adddate(sysdate(),1))";
	$updateresult = mysql_query($updateq);
}

function setup_session($usernum,$user,$name,$type){
	  $_SESSION['LOGGEDIN'] = 'YES';
	  $_SESSION['USERNUM'] = $usernum;
	  $_SESSION['USER'] = $user;
	  $_SESSION['NAME'] = $name;
	  $_SESSION['TYPE'] = $type;
	  update_login();
}

/* Logout the user*/
function logout(){
/* Destroyes cookie and session */
	$_SESSION['LOGGEDIN'] = 'NO';
	session_destroy();
  	unset($_SESSION);
	
	/* Delete the cookie from the table */
	dblogin();
	$id = $_COOKIE['fnt_id'];
	$query=
	"DELETE FROM COOKIE WHERE ID = $id";
	$result = mysql_query($query);
	
    setcookie("fnt_id","",time()-3600);
    setcookie("fnt_key","",time()-3600);
}



/* Update the last login time */
function update_login(){
	update('PLAYERS','lst_login','sysdate()','player_id',$_SESSION['USERNUM']);
}

function wipe_active(){
	dblogin();
	$query = 
	"update players p
	set p.gamevote = (select if(DATEDIFF(curdate(),z.game_day) > 14, 'N','Y')
					from
					(select y.login, p.game_day
					   from
						(select pl.login, max(ifnull(t.post_id,0)) as \"MAX_GAMEID\"
						  from players pl
						  join tourny_vote_table t
							on pl.login = t.player
						  group by pl.login) y
					   join tourny_post_table p
						 on y.max_gameid = p.post_id) z
					where p.login = z.login)";
	$result = mysql_query($query);
}

/*************************************************************
                    Player stuff  + Stats
 *************************************************************/
/* Update the last vote time */
function update_vote(){
	update('PLAYERS','lst_vote','sysdate()','player_id',$_SESSION['USERNUM']);
}
/* Update the tot_gp for the player */
function update_gp($tot_gp){
	update('PLAYERS','lst_vote',$tot_gp,'player_id',$_SESSION['USERNUM']);
}

/*  Print functions */
/* function to print out the last time logged in*/
function last_loggedin(){
	dblogin();
	$query = 
	"select lst_login from PLAYERS p where p.player_id = ".$_SESSION['USERNUM'];
	if($result = mysql_query($query)){
		if($row = mysql_fetch_array($result)){
			echo 'Last Logged in at: ',$row["lst_login"],'<br>';
		}
	}	
}
/* function to print out the last time voted in*/
function last_voted(){
	dblogin();
	$query = 
	"select lst_vote from PLAYERS p where p.player_id = ".$_SESSION['USERNUM'];
	if($result = mysql_query($query)){
		if($row = mysql_fetch_array($result)){
			echo 'Last Voted at: ',$row["lst_vote"],'<br>';
		}
	}	
}
/* function to print out the games owned by me*/
function mygames(){
	if(loggedin()){
		dblogin();
		$query = 
		"select gameid from GAMES p where p.owner = ".$_SESSION['USERNUM'];
		if($result = mysql_query($query)){
			while($row = mysql_fetch_array($result)){
				print_gamename($row["gameid"]);
			}
		}
	}	
}
/* function to print out the name of the player */
function player_name($player_id){
	dblogin();
	$query = 'select name from PLAYERS p where p.player_id = '.$player_id;
	 if($result = mysql_query($query)){
		if($row = mysql_fetch_array($result)){
			return $row['name'];
		}
	}
	return '';
}

function print_gamename($gameid){
	dblogin();
	$query = 
	"select gameid, game from GAMES p where p.gameid = ".$gameid;
	if($result = mysql_query($query)){
		if($row = mysql_fetch_array($result)){
			echo $row["game"],'<br>';
		}
	}
}	


function show_status($type, $num){
	dblogin();
echo '   <script type="text/javascript">
	$(\'.addme\').bind(\'click\', function() {
		$(\'#stat_cont  ul\').tabs(\'add\', $(this).attr("id"), $(this).attr("title"));
	});

        </script>	';

	if($type == 'ALL'){
		/* Show all of the stats */
		
		$query =
		'select x.*
		from
		(select p.name, p.player_id, sum(ifnull(amount,0)) as "AMT"
		  from PLAYERS p
		  left outer join GAMEPT t
		    on p.player_id = t.player_id
		  group by p.player_id) x
		 order by x.amt DESC'; 



		 if($result = mysql_query($query)){
			while($row = mysql_fetch_array($result)){

	echo '					<div id="player">
								<div id="status" style="width: 100%"></div>
								<h1 class="addme" id="Gen_Scripts/status.php" title="',$row['name'],'">',$row['name'],'</h1>
								<h2> ',$row['AMT'],'</h2>
							</div>';
			}
		}	
	}
	if($type == 'TID'){
		/* Show all of the stats for the tourny*/
		
		$query =
		'select x.*
		from
		(select p.name, p.player_id, sum(ifnull(amount,0)) as "AMT"
		  from PLAYERS p
		  left outer join 
		  	(select * from GAMEPT t where t.t_id = '.$num.') t
		    on p.player_id = t.player_id
		  group by p.player_id) x
		 order by x.amt DESC'; 
		 if($result = mysql_query($query)){
			while($row = mysql_fetch_array($result)){
	echo '					<div id="player">
								<div id="status" style="width: 100%"></div>
								<h1 id="Gen_Scripts/status.php" class="addme" title="',$row['name'],'">',$row['name'],'</h1>
								<h2> ',$row['AMT'],'</h2>
							</div>';
			}
		}	
	}	
	if($type == 'PLAYER'){
		/*  show the stats of the player */
	}	
}


?>